package com.itheima.utils;

import com.itheima.service.RoleService;
import com.itheima.service.StudentService;
import com.itheima.service.UserService;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Create By Awen on 2021/8/25
 *
 * @author Awen
 */
public class BeanFactory {
    //定义map容器，用于存放解析到的全限定名
    private static Map<String,String> beanUrlMap = new HashMap<>();
    static {
        //解析配置文件，获取需要创建的类的全限定名
        ResourceBundle bundle = ResourceBundle.getBundle("beans");
        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String beanUrl = bundle.getString(key);
            //将解析到的key-value存放到value中
            beanUrlMap.put(key, beanUrl);
        }
    }

    /**
     *
     * @param id 是beans.properties中的key
     * @return
     */
    public static Object getBean(String id){
        Object obj = null;
        try {
            //获取对应的类的全限定名
            String beanUrl = beanUrlMap.get(id);
            //反射创建对象
            obj = Class.forName(beanUrl).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }



    public static void main(String[] args) {
        UserService service1 = (UserService)BeanFactory.getBean("UserService");
        System.out.println(service1);
        RoleService service2 = (RoleService)BeanFactory.getBean("RoleService");
        System.out.println(service2);
        StudentService service3 = (StudentService)BeanFactory.getBean("StudentService");
        System.out.println(service3);
    }


}
